package edu.henu.personnel.controller;

import edu.henu.personnel.entity.User;
import edu.henu.personnel.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @program: PersonnelProject
 * @description: 用户管理控制器
 * @author: zhuyang
 * @create: 2019-05-13 10:59
 */

@Slf4j
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public String list(Model model) {
        List<User> userList = userService.getAllUser();
        model.addAttribute("userList", userList);
        return "user/list";
    }

    @GetMapping("/user")
    public String toAddUser() {
        return "user/add";
    }

    @PostMapping("/user")
    public String addUser(User user, Model model) {
        user.setUstatus("在线");
        int result = userService.addUser(user);
        return "redirect:/users";
    }

    @GetMapping("/user/{uid}")
    public String toEditPage(@PathVariable("uid") String uid, Model model) {
        User user = userService.getUserInfoById(uid);
        model.addAttribute("user", user);
        return "user/modifyPwd";
    }

    @PutMapping("/user")
    public String updateUser(User user, Model model) {
        int result = 0;
        User tempUser = userService.getUserInfoById(user.getUid());
        String oldPwd = tempUser.getUpwd();
        if (oldPwd.equals(user.getUpwd())) {
            tempUser.setUpwd(user.getUmemo());
            result = userService.updateUserPwd(tempUser);
        }

        if (result == 1) {
            model.addAttribute("result", "修改成功，请重新登录");
            return "login";
        } else {
            model.addAttribute("result", "修改密码失败，请重试");
            return "redirect:/user/" + user.getUid();
        }
    }

    @DeleteMapping("/user/{uid}")
    public String deleteUser(@PathVariable("uid") String uid, Model model) {
        int result = userService.deleteUser(uid);
        return "redirect:/users";
    }
}
















